package sourceagile.server.gitFileRepository;

import java.io.File;

import org.codehaus.jettison.json.JSONArray;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand.ListMode;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

public class ListGitFiles {

	public static JSONArray listEntries(String projectURL, String projectName,
			String username, String password) {

		JSONArray entries = new JSONArray();

		String projectPath = System.getProperty("java.io.tmpdir") + projectName;

		File tempFile = new File(projectPath);

		deleteDir(tempFile);

		Git git;

		if (username != null) {

			CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
					username, password);

			git = Git.cloneRepository().setURI(projectURL)
					.setDirectory(tempFile).setBranch("refs/heads/master")
					.setCredentialsProvider(credentialsProvider).call();
		} else {

			git = Git.cloneRepository().setURI(projectURL)
					.setDirectory(tempFile).setBranch("refs/heads/master")
					.call();
		}

		for (Ref b : git.branchList().setListMode(ListMode.ALL).call())
			System.out.println("(standard): cloned branch " + b.getName());

		File[] files = git.getRepository().getWorkTree().listFiles();

		for (File file : files) {

			if (!".git".equals(file.getName())) {

				entries = listSubDirectory(file, entries, projectPath);
			}
		}

		return entries;
	}

	/**
	 * Deletes all files and subdirectories under dir. Returns true if all
	 * deletions were successful. If a deletion fails, the method stops
	 * attempting to delete and returns false.
	 * 
	 */
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {

					System.out.println(dir);
					return false;

				}
			}
		}

		// The directory is now empty so delete it
		return dir.delete();
	}

	public static JSONArray listSubDirectory(File dir, JSONArray entries,
			String projectPath) {

		if (dir.isDirectory()) {

			String[] children = dir.list();

			for (int i = 0; i < children.length; i++) {

				listSubDirectory(new File(dir, children[i]), entries,
						projectPath);
			}

		} else {

			entries.put(ConvertFileToJson.convertFromGit(dir, projectPath));
		}

		return entries;
	}

}
